﻿using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AdHocReports
{
    public static class ExcelExport
    {
        public static void Export(string fileName, string cssFile, Table table, HttpResponse response)
        {
            if ((fileName != null) && (fileName.Length > 0) && (table != null))
            {
                string sStyle = string.Empty;

                using (System.IO.StreamReader iosr = new System.IO.StreamReader(cssFile))
                {
                    sStyle = iosr.ReadToEnd();
                    iosr.Close();
                }

                StringBuilder sb = new StringBuilder();
                StringWriter sw = new StringWriter(sb);
                Html32TextWriter tw = new Html32TextWriter(sw);
                table.RenderControl(tw);
                sb.ToString();

                response.AppendHeader("Content-disposition", "attachment; filename=report.xls");
                response.ContentType = "application/ms-excel";
                response.BufferOutput = true;
                response.Write("<html><head><style>" + sStyle + "</style></head><body>" + sb.ToString() + "</body></html>");
            }
        }
    }
}
